const RQ = require("request");
const Util = require("util");
const Logger = require("pomelo-logger").getLogger("Utils", "AccessToken");

const DB = require("lowdb")(__dirname + "/../config/data.json");
const Consts = require("../config/consts.json");


// Used For JSSDK
RQ(Util.format(Consts.token_url, Consts.appid, Consts.secret), function (err, res, body) {
    Logger.debug("Load access_token [ %s ] [ %s ] err: ", res.statusCode, body, err);

    if (err || res.statusCode != 200) {
        Logger.error("Load access_token Failed With Code [ %s ] err: ", res.statusCode, err);
        return;
    }

    var data;
    try {
        data = JSON.parse(body);
    } catch (e) {
        Logger.error("Load access_token Fail With Invalid JSON Body [ %s ]", body);
        return;
    }

    DB.set("jssdk.access_token", data.access_token).value();


    RQ(Util.format(Consts.ticket_url, data.access_token), function (err, res, body) {
        Logger.debug("Load jsapi_ticket [ %s ] [ %s ] err: ", res.statusCode, body, err);

        if (err || res.statusCode != 200) {
            Logger.error("Load jsapi_ticket Failed With Code [ %s ] err: ", res.statusCode, err);
            return;
        }

        var data;
        try {
            data = JSON.parse(body);
        } catch (e) {
            Logger.error("Load jsapi_ticket Fail With Invalid JSON Body [ %s ]", body);
            return;
        }

        if (data.errcode == 0) {
            DB.set("jssdk.jsapi_ticket", data.ticket).value();
            DB.set("jssdk.expire_in", (new Date()).valueOf() + 7200 * 1e3).value();
        }
    });

});
